package com.txf.simple.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @title
 * @note Created by Chaosxing on 2016/10/24.
 */
public class JsonTools {
    public static String toJson(Object value) {
        return JSON.toJSONString(value);
    }
    public static final JSONObject parseObject(String json) {
        try {
            return JSON.parseObject(json);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T parseObject(String json, Class<T> cls) {
        try {
            return JSON.parseObject(json, cls);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> List<T> parseArray(String jsonString, Class<T> cls) {
        try {
            return JSON.parseArray(jsonString, cls);
        } catch (Exception e) {
            return new ArrayList<T>();
        }
    }

    public static <T> T fromJson(String json, Class<T> cls) {
        try {
            return new Gson().fromJson(json, cls);
        } catch (Exception e) {
            return null;
        }
    }
    public static <T> T fromJson(String jsonString, Type typeOfT) {
        try {
            return new Gson().fromJson(jsonString, typeOfT);
        } catch (Exception e) {
            return null;
        }
    }
    public final static <T> Type buildType(Class<T> cls) {
        return new TypeToken<List<T>>() {
        }.getType();
    }

}
